package com.jw.elasticsearch.springboot.controller;

import com.jw.elasticsearch.springboot.config.EsClientConfig;
import com.jw.elasticsearch.springboot.index.IndexBuilder;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.core.MainResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/es/")
public class EsController {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private EsClientConfig clientConfig;

    @Autowired
    private IndexBuilder indexBuilder;

    /**
     * 获取连接信息
     */
    @GetMapping("getConnectionInfo")
    public void getConnectionInfo() {
        RestHighLevelClient restHighLevelClient = clientConfig.getConnection();
        try {
            MainResponse mainResponse = restHighLevelClient.info(RequestOptions.DEFAULT);
            logger.info("\n ===============>>> connection info <<<===============\n cluster name: {}; \n cluster uuid: {}; \n " +
                            "node name: {}; \n tag line: {}; \n version: {}\n ",
                    mainResponse.getClusterName(), mainResponse.getClusterUuid(), mainResponse.getNodeName(),
                    mainResponse.getTagline(), mainResponse.getVersion().getLuceneVersion());
        } catch (IOException e) {
            logger.error("es error: {}", e.getMessage());
        }
    }

    @ResponseBody
    @GetMapping("createIndex")
    public void createIndex() {
        indexBuilder.createIndex();
    }

    /**
     * 判断某个索引是否存在
     */
    @GetMapping("exists")
    public void getIndices() {
        RestHighLevelClient restHighLevelClient = clientConfig.getConnection();
        GetIndexRequest getIndexRequest = new GetIndexRequest("re");
        try {
            Boolean exists = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
            logger.info("es exists: {}", exists);
        } catch (IOException e) {
            logger.error("es error: {}", e.getMessage());
        }
    }

    /**
     * 添加文档
     */
    @ResponseBody
    @GetMapping("add")
    public void add() {
        indexBuilder.add();
    }

    /**
     * 查询文档信息
     */
    @ResponseBody
    @GetMapping("getDocument")
    public void getDocument(){
        try {
            indexBuilder.getDocument();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
